'use strict';
const express = require('express');
const Dysmsapi20170525 = require('@alicloud/dysmsapi20170525');
const OpenApi = require('@alicloud/openapi-client');
const Util = require('@alicloud/tea-util');
const router = express.Router();
class SmsClient {
    static createClient() {
        let config = new OpenApi.Config({
            accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,
            accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET,
        });
        config.endpoint = 'dysmsapi.aliyuncs.com';
        return new Dysmsapi20170525.default(config);
    }

    static async sendSms(phoneNumber, templateParam) { 
        const client = SmsClient.createClient();
        const sendSmsRequest = new Dysmsapi20170525.SendSmsRequest({
            phoneNumbers: phoneNumber,
            signName: process.env.ALIBABA_CLOUD_ACCESS_SINGNAME,
            templateCode: process.env.ALIBABA_CLOUD_ACCESS_TEMPLATECODE,
            templateParam: JSON.stringify({ code: templateParam }),
        });

        const runtime = new Util.RuntimeOptions({});
        try {
            const response = await client.sendSmsWithOptions(sendSmsRequest, runtime);
            return response;
        } catch (error) {
            console.error('短信发送失败:', error);
            throw error;
        }
    }
}

router.post('/send_sms', async (req, res) => {
    const { phone, code } = req.body;
    try {
        const response = await SmsClient.sendSms(phone, code);
        res.json({ success: true, data: response, code: code });
    } catch (error) {
        res.status(500).json({ success: false, error: error.message });
    }
});


module.exports = router;